/*General functions*/
function $_(idElement){
	return document.getElementById(idElement);
}

function $F_(idElement){
   var element = $_(idElement);
   switch(element.type){
   	 case 'select-one':
       return element.options[element.selectedIndex].value;
       break;
     case 'radio':
     case 'checkbox':
       return element.checked;
       break;
     case 'text':
     case 'password':
     case 'textarea':
     case 'hidden':
       return element.value;
       break;
     default:
       return element.innerHTML;
   }
}

function killEvent(elm, evType, fn, useCapture){
       if (elm.removeEventListener) {
                elm.removeEventListener(evType, fn, useCapture);
        return true;
        }
        else if (elm.detachEvent) {
                var r = elm.detachEvent('on' + evType, fn);
                return r;
        }
        else {
                elm['on' + evType] = null;
        }
}
function addEventMy(elm, evType, fn, useCapture) {
        if (elm.addEventListener) {
                elm.addEventListener(evType, fn, useCapture);
        return true;
        }
        else if (elm.attachEvent) {
                var r = elm.attachEvent('on' + evType, fn);
                return r;
        }
        else {
                elm['on' + evType] = fn;
        }
}
/*-----------------*/

function changeCategory(){
	var url = 'index3.php';
	function showResponse(data){
	    $_('ordering').innerHTML = data;
	}
    jQuery.get(
     url,
     {
    	option:  "com_unocart",
    	act:     "ajax",
    	task:    "showCategory",
    	no_html: "1",
    	catid:   $F_("category_parent_id")
     },
      showResponse
    );
}


function changeCategoryHref(idCategory){
	location.href = 'index2.php?option=com_unocart&act=categories&catid=' + idCategory;
}

function showHideSEF(){
   return;
   if ($_('useInternalSEF').checked){
     $_('show_sef').style.display = '';
     $_('show_lang').style.display = '';
     $_('show_slash').style.display = '';
   } else {
   	 $_('show_sef').style.display = 'none';
   	 $_('show_lang').style.display = 'none';
   	 $_('show_slash').style.display = 'none';
   }
}


function checkDirectory(id, directory){
	var url = 'index3.php';
    var pars = 'option=com_unocart&act=ajax&task=checkDirectory&no_html=1&directory=' + directory;
    function showResponse(data){
       var response = eval(data);
       $_(id).innerHTML = response.text;
       $_(id).className = (response.isWrite == 1) ? ('unocart_green') : ('unocart_red');
    }
    jQuery.get(
     url,
     {
    	option:    "com_unocart",
    	act:       "ajax",
    	task:      "checkDirectory",
    	no_html:   "1",
    	directory: directory
     },
      showResponse
    );
}


function setDefaultSize(width, height, param){
   $_(param + '_width_image').value = width;
   $_(param + '_height_image').value = height;
   $_(param + '_width_image').disabled = true;
   $_(param + '_height_image').disabled = true;
}

function setOriginalSize(param){
   $_(param + '_width_image').disabled = true;
   $_(param + '_height_image').disabled = true;
   $_(param + '_width_image').value = 0;
   $_(param + '_height_image').value = 0;
}

function setManualSize(param){
   $_(param + '_width_image').disabled = false;
   $_(param + '_height_image').disabled = false;
   $_(param + '_width_image').value = '';
   $_(param + '_height_image').value = '';
}

function setFullOriginalSize(param){
   $_(param + '_width_image').disabled = true;
   $_(param + '_height_image').disabled = true;
   $_(param + '_width_image').value = '';
   $_(param + '_height_image').value = '';
}

function setFullManualSize(param){
   $_(param + '_width_image').disabled = false;
   $_(param + '_height_image').disabled = false;
   $_(param + '_width_image').value = '';
   $_(param + '_height_image').value = '';
}

function addToCart(value, idProduct, fullpath){
    var pars = 'option=com_unocart&act=ajax_f&task=add_to_cart&no_html=1&product_id=' + idProduct + '&quantity=' + value;
	jQuery.ajax({
		type: "GET",
		url: fullpath + '/index2.php',
		data: pars,
		dataType: "xml",
		beforeSend:function(){
	       jQuery('#unocart_button').hide();
	       jQuery('#unocart_image_loading').show();
		},
		complete:function(data){
	       jQuery('#unocart_button').show();
	       jQuery('#unocart_image_loading').hide();
           jQuery(data.responseText).find("result").each(function(){
          	  text     = jQuery(this).attr('text');
          	  quantity = jQuery(this).attr('quantity');
          	  summ	   = jQuery(this).attr('summ');
           });
           alert (text);
		   if ($_('unocart_module_cart')){
		      $_('unocart_quantity_products').innerHTML = quantity;
		      $_('unocart_summ_product').innerHTML = summ;
		   }
		}
	})
}

function highlightField(field){
    $_(field).style.backgroundColor = "#FDC055";
}

function unhighlightField(formName){
    var form = document.forms[formName];
    var countElements = form.length;
    for (i = 0; i < countElements; i++){
       	if (form.elements[i].type == 'button' || form.elements[i].type == 'submit' || form.elements[i].type == 'radio' || form.elements[i].type == 'hidden') continue;
       	form.elements[i].style.backgroundColor = "#FFFFFF";
    }
}


function isEmpty(value){
	var pattern = /\S/;
	return ret = (pattern.test(value)) ? (0) : (1);
}

function checkMail(value){
   var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   return ret = (pattern.test(value)) ? (1) : (0);
}

function Equal(value1, value2){
  return (value1 == value2)
}



function validateRegistrationForm(fullpath, formName){
    var arrayId            = new Array('title', 'u_name', 'f_name', 'l_name', 'street', 'zip', 'city', 'state', 'country', 'email', 'phone', 'password', 'agb');
    var arrayType          = new Array('notn',  'nem',    'nem',    'nem',    'nem',    'nem', 'nem',  'nem',   'notn',    'em',    'nem',   'eqne', 'chk');
    var arrayParams        = new Array('', '', '', '', '', '', '', '', '', '', '', 'password_2', '');
    var arrayErrorMessages = new Array('', '', '', '', '', '', '', '', '', '', '', '', '');
    var typeShowError      = 2;
	var backCurrent = '#FFFFFF';
	var backColor   = '#FDC055';
	var myForm = new validateForm(formName, arrayId, arrayType, arrayParams, arrayErrorMessages, typeShowError, backCurrent, backColor);
	var error = (myForm.validate()) ? (1) : (0);
	if (!error){
		return false;
	} else {
        function showResponse(originalRequest){
           if (originalRequest != 1){
           	  alert (originalRequest);
           	  return false;
           } else {
           	  document.forms[formName].submit();
           }
        }
        var url = fullpath + '/index2.php';
	    jQuery.get(
	     url,
	     {
	    	option:  "com_unocart",
	    	act:     "ajax_f",
	    	task:    "check_user",
	    	no_html: "1",
	    	username:$F_('u_name')
	     },
	      showResponse
	    );
        return false;
	}
}

function validateRegistration2Form(livepath, formName){
    var arrayId            = new Array('title', 'u_name', 'f_name', 'l_name', 'street', 'zip', 'city', 'state', 'country', 'email', 'phone', 'agb');
    var arrayType          = new Array('notn',  'nem',    'nem',    'nem',    'nem',    'nem', 'nem',  'nem',   'notn',    'em',    'nem',   'chk');
    var arrayParams        = new Array('', '', '', '', '', '', '', '', '', '', '', '');
    var arrayErrorMessages = new Array('', '', '', '', '', '', '', '', '', '', '', '');
    var typeShowError      = 2;
	var backCurrent = '#FFFFFF';
	var backColor   = '#FDC055';
    if ($_('delivery_adress_2')){
        if ($F_('delivery_adress_2')){
		    arrayId   		   = arrayId.concat('d_title', 'd_f_name', 'd_l_name', 'd_street', 'd_zip', 'd_city', 'd_state', 'd_phone');
		    arrayType 		   = arrayType.concat('notn', 'nem', 'nem', 'nem', 'nem', 'nem', 'nem', 'nem');
		    arrayParams		   = arrayParams.concat('', '', '', '', '', '', '', '');
		    arrayErrorMessages = arrayErrorMessages.concat('', '', '', '', '', '', '', '');
        }
    }
	var myForm = new validateForm(formName, arrayId, arrayType, arrayParams, arrayErrorMessages, typeShowError, backCurrent, backColor);
	return error = (myForm.validate()) ? (true) : (false);
}


function validateFormAdvancedSearch(formName){
    var arrayId            = new Array('date_from', 'date_to', 'price_from', 'price_to');
    var arrayType          = new Array('date|em', 'date|em', 'fl|em', 'fl|em');
    var arrayParams        = new Array('', '');
    var arrayErrorMessages = new Array('', '');
    var typeShowError      = 2;
	var backCurrent = '#FFFFFF';
	var backColor   = '#FDC055';
    var myForm = new validateForm(formName, arrayId, arrayType, arrayParams, arrayErrorMessages, typeShowError, backCurrent, backColor);
    myForm.validate();
}

prevHandler = false;
function showPaymentForm(paymentMethod){
	var tablePayments = $_('table_payments');
    var countRows = tablePayments.rows.length;
    // Vytyaguju vsi tr z payments
    for (var i = 1; i < countRows; i=i+2){
        var trCurrent = tablePayments.rows[i];
        if (trCurrent.id == 'tr_payment[' + paymentMethod + ']'){
        	styleDisplay = '';
        	funcHandler = trCurrent.id
        } else {
        	styleDisplay = 'none';
        }
        trCurrent.style.display = styleDisplay;
    }
    var reg = /\[(.*)\]/;
    reg.test(funcHandler);
    funcHandler = RegExp.$1;
    if (prevHandler) killEvent($_('payment_submit'), 'click', 'function' == typeof(window[prevHandler]) ? window[prevHandler] : null, false);
    addEventMy($_('payment_submit'), 'click', 'function' == typeof(window[funcHandler]) ? window[funcHandler] : null, false);
    prevHandler = funcHandler;
}

function isInt_5_8(value){
	var pattern = /^(\d){5,8}$/;
	return ret = (pattern.test(value)) ? (1) : (0);
}


function validateShippingMethods(){
    var tableShip = $_('table_shippings');
    var inputs = tableShip.getElementsByTagName('input');
    for (var i=0; i<inputs.length; i++){
    	if (inputs[i].type != 'radio') continue;
        if (inputs[i].checked) return true;
    }
    return false;
}

function addAttributValue(attributId){
    var attrValueId = $F_('value_id' + attributId);
    if (attributId > 0 && attrValueId > 0) {
      if ($_('attr_value_' + attrValueId).style.display == 'none'){
        $_('attr_value_' + attrValueId).style.display = '';
      	$_('input_attr_value_' + attrValueId).disabled = false;
      } else {
      	$_('input_attr_value_' + attrValueId).focus();
      }
    }
}

function addAttributAll(attributId){
	jQuery("tr.attr_" + attributId + "> td > input:text").each(
		function enabledAttr(){
			$_(this.id).disabled = '';
		}
	) 
	jQuery("tr.attr_" + attributId).show();
}

function hideElement(idElement){
    $_(idElement).style.display = 'none';
}

function disableElement(idElement){
    $_(idElement).disabled = true;
}

function verifyStatus(orderStatus, orderId, message, extended, limit){
   if (extended == 0){
	   var statusNewId = $F_('select_status_id' + orderId);
	   if (statusNewId == orderStatus){
	   	 alert (message);
	   	 return;
	   } else {
	     var isChecked = ($_('order_check_id_' + orderId ).checked) ? ('&notify=1') : ('');
	     location.href = 'index2.php?option=com_unocart&act=orders&task=update_status&order_id=' + orderId + '&order_status=' + statusNewId + limit + isChecked;
	   }
   } else {
       var statusNewId = $F_('order_status');
       if (statusNewId == orderStatus){
       	   alert (message);
       	   return;
       } else {
	     var isChecked = ($_('notify').checked) ? ('&notify=1') : ('&notify=0');
	     var includeComment = ($_('include').checked) ? ('&include=1') : ('&include=0');

	     location.href = 'index2.php?option=com_unocart&act=orders&task=update_one_status&order_id=' + orderId + '&order_status=' + statusNewId + isChecked + includeComment + '&comments=' + $F_('comments');
       }
   }
}


function changeSortCountProducts(changeOrder){
    if (changeOrder){
       $_('orderby').value = $_('orderby').value ^ 1;
    }
    $_('sort_count').submit();
}

function showVideo(idElement){
	jQuery('.video_full').hide();
    $_('hide_' + idElement).href = $_(idElement).href;
	jQuery('#main_image').hide();
	jQuery('#hide_' + idElement).show();
	jQuery('#hide_' + idElement).media();
}

function showImage(srcImage){
 $_('main_image').src = srcImage;
 jQuery('#main_image').show();
 jQuery('.video_full').hide();
}

function playMusic(idElement){
	jQuery('#' + idElement).media( { width: 100, height: 20, autoplay:true } );
}

function addExtendField(){
	var inputNumber = document.createElement('input');
	inputNumber.setAttribute('type', 'text');
	inputNumber.setAttribute('class', 'inputbox');
	inputNumber.setAttribute('size', '2');
	inputNumber.setAttribute('name', 'number[]');

	var inputTitle = document.createElement('input');
	inputTitle.setAttribute('type', 'text');
	inputTitle.setAttribute('class', 'inputbox');
	inputTitle.setAttribute('name', 'title[]');
	
	var inputTime = document.createElement('input');
	inputTime.setAttribute('type', 'text');
	inputTime.setAttribute('class', 'inputbox');
	inputTime.setAttribute('name', 'time[]');
	
	var inputFile = document.createElement('input');
	inputFile.setAttribute('type', 'file');
	inputFile.setAttribute('class', 'inputbox');
	inputFile.setAttribute('name', 'files[]');
	
	var td_1 = document.createElement('td');
	td_1.appendChild(inputNumber);	

	var td_2 = document.createElement('td');
	td_2.appendChild(inputTitle);	
	
	var td_3 = document.createElement('td');
	td_3.appendChild(inputTime);	

	var td_4 = document.createElement('td');
	td_4.appendChild(inputFile);	

	var tr = document.createElement('tr');
	tr.appendChild(td_1);	
	tr.appendChild(td_2);	
	tr.appendChild(td_3);
	
	tr.appendChild(td_4);
	
	var currentNode = $_('last_tr');
	currentNode.parentNode.insertBefore(tr, currentNode);
}

function addFieldShPrice(){
	var inputPrice = document.createElement('input');
	inputPrice.setAttribute('type', 'text');
	inputPrice.setAttribute('class', 'inputbox');
	inputPrice.setAttribute('name', 'shipping_price[]');

	var inputPackagePrice = document.createElement('input');
	inputPackagePrice.setAttribute('type', 'text');
	inputPackagePrice.setAttribute('class', 'inputbox');
	inputPackagePrice.setAttribute('name', 'shipping_package_price[]');
	
	var inputMinWeight = document.createElement('input');
	inputMinWeight.setAttribute('type', 'text');
	inputMinWeight.setAttribute('class', 'inputbox');
	inputMinWeight.setAttribute('name', 'shipping_weight_from[]');
	
	var inputMaxWeight = document.createElement('input');
	inputMaxWeight.setAttribute('type', 'text');
	inputMaxWeight.setAttribute('class', 'inputbox');
	inputMaxWeight.setAttribute('name', 'shipping_weight_to[]');
	
	var td_1 = document.createElement('td');
	td_1.appendChild(inputPrice);	

	var td_2 = document.createElement('td');
	td_2.appendChild(inputPackagePrice);	
	
	var td_3 = document.createElement('td');
	td_3.appendChild(inputMinWeight);	

	var td_4 = document.createElement('td');
	td_4.appendChild(inputMaxWeight);	

	var tr = document.createElement('tr');
	tr.appendChild(td_1);	
	tr.appendChild(td_2);	
	tr.appendChild(td_3);
	tr.appendChild(td_4);
	
	var currentNode = $_('last_tr');
	currentNode.parentNode.insertBefore(tr, currentNode);	
}

function showHideReview(){
	jQuery('#unocart_review_write').show();
}

function updateGross(){
	var repl = new RegExp("\,", "i");
	var percent = $_('product_tax_id')[$_('product_tax_id').selectedIndex].text;
	var pattern = /(\d*\.?\d*)%\)$/
	pattern.test(percent);
	percent = RegExp.$1; 
	var priceNet = $F_('product_price_net');
	$_('product_price_gross').value = Round(priceNet * (1 + percent / 100), 2);
}

function Round(value, numCount){
	var ret = parseFloat(Math.round(value * Math.pow(10, numCount)) / Math.pow(10, numCount)).toString();
	return (isNaN(ret)) ? (0) : (ret);
}

function updateNet(){
	var repl = new RegExp("\,", "i");
	var percent = $_('product_tax_id')[$_('product_tax_id').selectedIndex].text;
	var pattern = /(\d*\.?\d*)%\)$/
	pattern.test(percent);
	percent = RegExp.$1; 
	var priceGross = $F_('product_price_gross');
	$_('product_price_net').value = Round (priceGross / (1 + percent / 100), 2);
}

function addNewPrice(){
	var inputQuantityStart = document.createElement('input');
	inputQuantityStart.setAttribute('type', 'text');
	inputQuantityStart.setAttribute('class', 'inputbox');
	inputQuantityStart.setAttribute('name', 'quantity_start[]');

	var inputQuantityFinish = document.createElement('input');
	inputQuantityFinish.setAttribute('type', 'text');
	inputQuantityFinish.setAttribute('class', 'inputbox');
	inputQuantityFinish.setAttribute('name', 'quantity_finish[]');
	
	var inputProductAddPrice = document.createElement('input');
	inputProductAddPrice.setAttribute('type', 'text');
	inputProductAddPrice.setAttribute('class', 'inputbox');
	inputProductAddPrice.setAttribute('name', 'product_add_price[]');
	
	var inputCheckboxDelete = document.createElement('input');
	inputCheckboxDelete.setAttribute('type', 'checkbox');
	inputCheckboxDelete.setAttribute('name', 'product_add_price_delete[]');


	var td_1 = document.createElement('td');
	td_1.appendChild(inputQuantityStart);	

	var td_2 = document.createElement('td');
	td_2.appendChild(inputQuantityFinish);	
	
	var td_3 = document.createElement('td');
	td_3.appendChild(inputProductAddPrice);	

	var td_4 = document.createElement('td');
	td_4.appendChild(inputCheckboxDelete);	

	var tr = document.createElement('tr');
	tr.appendChild(td_1);	
	tr.appendChild(td_2);	
	tr.appendChild(td_3);
	tr.appendChild(td_4);
	
	var currentNode = $_('last_tr_price');
	currentNode.parentNode.insertBefore(tr, currentNode);	
}

function sendToAdmin(){
	var url = 'index2.php';
	function showResponse(data){
	    alert (data);
		//$_('ordering').innerHTML = data;
	}
    jQuery.post(
     url,
     {
    	option:  "com_unocart",
    	act:     "ajax_f",
    	task:    "sendAdmin",
    	product_id: $F_('product_id'),
    	no_html: "1",
    	request_message:   $F_("request_message")
     },
      showResponse
    );
}

function deleteData() {
	var url = 'index2.php';
    function showResponse(data){
       $_('paypal_form').submit();
    }
    jQuery.get(
	     url,
	     {
	    	option:  "com_unocart",
	    	act:     "ajax_f",
	    	task:    "deleteData",
	    	no_html: "1",
            order_add_info: jQuery('#order_add_info').val()
	     },
	     showResponse
    );
    return false;
}

function sendFiles(){
    alert ('f');
    jQuery.load
}